const _ = require('lodash');
const moment = require("moment");

module.exports = class {
    constructor(app) {
        this.app = app;
        this.task = async (timeSpace) => {
            const tenants = await this.app.dbs.find("Tenant", {});

            _.map(tenants, async (tenant) => {
                const {tenantCode, tenantName} = tenant;
                console.log('assess task find tenants', tenantName, timeSpace);
                const data = {
                    timeSpace,
                    tenantCode, tenantName,
                    timeStr: moment().format('YYYY-MM-DD HH:mm:ss'),
                    time: moment().valueOf()
                };
                const ts = moment().valueOf();
                const tsStart = moment().add(-30, 'minutes').valueOf();

                /**
                 * 统计主机
                 */
                const queryChiller = {
                    $match: {
                        tenantCode: tenantCode,
                        deviceType: {$regex: "制冷主机"},
                        // "points.ChillerRunning": 1,
                        "points.ActualRunningCapacity": {$gt: 25},
                        time: {$gt: tsStart, $lt: ts}
                    }
                };
                const chillerRes = await this.app.dbs.aggregate('IotReportData', [
                    queryChiller,
                    {
                        $group: {
                            _id: ['$deviceId', '$deviceName'], // 分组键，这里使用null因为我们不需要按任何字段分组，只是求平均值
                            // minSetTemp: {min: "$points.setTemp"},
                            chillerCapAvg: {$avg: "$points.ActualRunningCapacity"},
                            freezingOutTempSet: {$avg: "$points.ActiveCoolHeatSetpointTemperatureSV"},
                            EvapEnteringWaterTemp: {$avg: "$points.EvapEnteringWaterTemp"},
                            EvapLeavingWaterTemp: {$avg: "$points.EvapLeavingWaterTemp"}
                        }
                    }]);

                if (chillerRes.length === 0) {
                    console.log(tenant, 'chiller count is 0');
                    return;
                }
                let chillerCapa = 0;

                let _freezingOutTempSet = 0;

                _.map(chillerRes, (child) => {
                    const {chillerCapAvg, freezingOutTempSet} = child;
                    chillerCapa += chillerCapAvg;
                    _freezingOutTempSet += freezingOutTempSet;
                });
                let chillerAvg = chillerCapa / chillerRes.length;
                data['chiller'] = chillerRes;
                data['chillerCapAvg'] = chillerAvg;
                data['chillerRunCount'] = chillerRes.length;
                data['freezingOutTempSet'] = _freezingOutTempSet / chillerRes.length;
                /**
                 * 统计冷却塔
                 */
                const queryTower = {
                    $match: {
                        tenantCode: tenantCode,
                        deviceType: {$regex: "冷却塔"},
                        "points.coolingTowerFrequencyPV": {$gt: 20},
                        time: {$gt: tsStart, $lt: ts}
                    }
                };
                const towerRes = await this.app.dbs.aggregate('IotReportData', [
                    queryTower,
                    {
                        $group: {
                            _id: ['$deviceId', '$deviceName'], // 分组键，这里使用null因为我们不需要按任何字段分组，只是求平均值
                            value: {$avg: "$points.coolingTowerFrequencyPV"}
                        }
                    }]);
                let towerFreq = 0;
                _.map(towerRes, (child) => {
                    const {value} = child;
                    towerFreq += value;
                });
                let towerAvg = towerFreq / towerRes.length;
                data['towerFreq'] = towerRes;
                data['towerFreqAvg'] = isNaN(towerAvg) ? 0 : towerAvg;

                /**
                 * 统计冷冻泵
                 */
                const queryFPump = {
                    $match: {
                        tenantCode: tenantCode,
                        deviceType: {$regex: "冷冻水泵"},
                        "points.freezingPumpFrequencyPV": {$gt: 20},
                        time: {$gt: tsStart, $lt: ts}
                    }
                };
                const FPumpRes = await this.app.dbs.aggregate('IotReportData', [
                    queryFPump,
                    {
                        $group: {
                            _id: ['$deviceId', '$deviceName'], // 分组键，这里使用null因为我们不需要按任何字段分组，只是求平均值
                            value: {$avg: "$points.freezingPumpFrequencyPV"}
                        }
                    }]);
                let fpFreq = 0;
                _.map(FPumpRes, (child) => {
                    const {value} = child;
                    fpFreq += value;
                });
                let freezingPumpAvg = fpFreq / FPumpRes.length;
                data['freezingPumpFreq'] = FPumpRes;
                data['freezingPumpFreqAvg'] = isNaN(freezingPumpAvg) ? 0 : freezingPumpAvg;

                /**
                 * 统计冷却泵
                 */
                const queryCPump = {
                    $match: {
                        tenantCode: tenantCode,
                        deviceType: {$regex: "冷却水泵"},
                        "points.coolingPumpFrequencyPV": {$gt: 20},
                        time: {$gt: tsStart, $lt: ts}
                    }
                };
                const CPumpRes = await this.app.dbs.aggregate('IotReportData', [
                    queryCPump,
                    {
                        $group: {
                            _id: ['$deviceId', '$deviceName'], // 分组键，这里使用null因为我们不需要按任何字段分组，只是求平均值
                            value: {$avg: "$points.coolingPumpFrequencyPV"}
                        }
                    }]);
                let cpFreq = 0;
                _.map(CPumpRes, (child) => {
                    const {value} = child;
                    cpFreq += value;
                });
                let coolingPumpAvg = cpFreq / CPumpRes.length;
                data['coolingPumpFreq'] = FPumpRes;
                data['coolingPumpFreqAvg'] = isNaN(coolingPumpAvg) ? 0 : coolingPumpAvg;
                /**
                 * 统计电能
                 */


                const power = {};
                const powerResChiller = await this.app.dbs.aggregate('IotReportData', [
                    {
                        $match: {
                            tenantCode: tenantCode,
                            deviceType: {$regex: "制冷主机电表"},
                            time: {$gt: tsStart, $lt: ts}
                        }
                    },
                    {$sort: {time: 1}}, // 排序
                    {
                        $group: {
                            _id: ['$deviceId', "$deviceName"],
                            firstValue: {$first: "$status"},
                            lastValue: {$last: "$status"}
                        }
                    },
                    {$project: {_id: '$_id', value: {$subtract: ["$lastValue", "$firstValue"]}}}
                ]);
                power['chiller'] = powerResChiller;
                let chillerPower = 0;
                _.map(powerResChiller, item => {
                    const {value} = item;
                    chillerPower += value;
                });
                data['chillerPower'] = chillerPower;

                const powerResFPump = await this.app.dbs.aggregate('IotReportData', [
                    {
                        $match: {
                            tenantCode: tenantCode,
                            deviceType: {$regex: "冷冻水泵电表"},
                            time: {$gt: tsStart, $lt: ts}
                        }
                    },
                    {$sort: {time: 1}}, // 排序
                    {
                        $group: {
                            _id: ['$deviceId', "$deviceName"],
                            firstValue: {$first: "$status"},
                            lastValue: {$last: "$status"}
                        }
                    },
                    {$project: {_id: '$_id', value: {$subtract: ["$lastValue", "$firstValue"]}}}
                ]);
                power['freezingPump'] = powerResFPump;

                let freezingPumpPower = 0;
                _.map(powerResFPump, item => {
                    const {value} = item;
                    freezingPumpPower += value;
                });
                data['freezingPumpPower'] = freezingPumpPower;
                const powerResCPump = await this.app.dbs.aggregate('IotReportData', [
                    {
                        $match: {
                            tenantCode: tenantCode,
                            deviceType: {$regex: "冷却水泵电表"},
                            time: {$gt: tsStart, $lt: ts}
                        }
                    },
                    {$sort: {time: 1}}, // 排序
                    {
                        $group: {
                            _id: ['$deviceId', "$deviceName"],
                            firstValue: {$first: "$status"},
                            lastValue: {$last: "$status"}
                        }
                    },
                    {$project: {_id: '$_id', value: {$subtract: ["$lastValue", "$firstValue"]}}}
                ]);
                power['coolingPump'] = powerResCPump;

                let coolingPumpPower = 0;
                _.map(powerResCPump, item => {
                    const {value} = item;
                    coolingPumpPower += value;
                });
                data['coolingPumpPower'] = coolingPumpPower;

                const powerResTower = await this.app.dbs.aggregate('IotReportData', [
                    {
                        $match: {
                            tenantCode: tenantCode,
                            deviceType: {$regex: "冷却塔电表"},
                            time: {$gt: tsStart, $lt: ts}
                        }
                    },
                    {$sort: {time: 1}}, // 排序
                    {
                        $group: {
                            _id: ['$deviceId', "$deviceName"],
                            firstValue: {$first: "$status"},
                            lastValue: {$last: "$status"}
                        }
                    },
                    {$project: {_id: '$_id', value: {$subtract: ["$lastValue", "$firstValue"]}}}
                ]);
                power['tower'] = powerResTower;

                let towerPower = 0;
                _.map(powerResTower, item => {
                    const {value} = item;
                    towerPower += value;
                });
                data['towerPower'] = towerPower;
                data['power'] = power;

                const outTemp = await this.app.dbs.findOne("IotDevice", {deviceType: {$regex: "室外温湿度"}});
                if(outTemp){
                    data['outsideTemp'] = outTemp.status;
                    data['outsideHum'] = outTemp.points ? outTemp.points.hum : 0;
                }


                /**
                 * 获取设定值的平均值
                 */
                const query = {
                    $match: {
                        status: 1,
                        deviceType: {$regex: "末端空调"},
                        "points.model": 0,
                        tenantCode: tenantCode
                    }
                };
                const avgSet = await this.app.dbs.aggregate('IotDevice', [
                    query,
                    {
                        $group: {
                            _id: null, // 分组键，这里使用null因为我们不需要按任何字段分组，只是求平均值
                            // minSetTemp: {min: "$points.setTemp"},
                            avgSetTemp: {$avg: "$points.setTemp"}
                        }
                    }]);
                data['avgSetTemp'] = avgSet && avgSet.length > 0 && avgSet[0] ? avgSet[0].avgSetTemp : 0;
                /**
                 * 室内环境温度平均
                 */
                const avg = await this.app.dbs.aggregate('IotDevice', [
                    query,
                    {
                        $group: {
                            _id: null, // 分组键，这里使用null因为我们不需要按任何字段分组，只是求平均值
                            maxEnvTemp: {$max: "$points.envTemp"},
                            avgEnvTemp: {$avg: "$points.envTemp"}
                        }
                    }]);

                data['avgEnvTemp'] = avg && avg.length > 0 && avg[0] ? avg[0].avgEnvTemp : 0;
                data['maxEnvTemp'] = avg && avg.length > 0 && avg[0] ? avg[0].maxEnvTemp : 0;

                const list = await this.app.dbs.find('IotDevice', {deviceType: '制冷系统'});
                const result = {};
                _.map(list, item => {
                    const {deviceId, status, statusPath, points} = item;
                    if (status) result[deviceId + statusPath] = status;
                    if (statusPath === 'accCoolingCapacity') {
                        //   console.log('cooling capacity', points);
                        _.map(points, (value, key) => {
                            result[deviceId + key] = value;
                        });
                    }
                });
                data['iceSys'] = result;
                data["airRunCount"] = await this.app.dbs.count('IotDevice', {
                    status: 1,
                    deviceType: "末端空调",
                    "points.model": 0,
                    tenantCode: tenantCode
                });
                /**
                 * 获取大于25度的环境温度数量
                 */
                const cross25Res = await this.app.dbs.aggregate('IotDevice', [
                    query,
                    {
                        $match: {
                            "points.envTemp": {$gt: 25.5} // $gt 是大于的意思
                        }
                    },
                    {
                        $count: "cross25"
                    }
                ]);
                data['cross25'] = cross25Res && cross25Res.length > 0 && cross25Res[0] ? cross25Res[0].cross25 : 0;
                data['airCount'] = await this.app.dbs.count('IotDevice', {
                    deviceType: "末端空调",
                    tenantCode: tenantCode
                });

                console.log(data);
                const res = await this.app.dbs.insert('Assess', data);
            });
        };
        this.app.eventBus.on('AI_ASSESS', this.task);
    }
};
